package com.sec.etech.ism.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sec.etech.ism.model.IsmAppSetting;
import com.sec.etech.ism.model.IsmServiceDef;
import com.sec.etech.ism.service.IsmAppSettingService;
import com.sec.etech.ism.service.IsmCommonService;
import com.sec.etech.ism.service.IsmMethodService;
import com.sec.etech.ism.service.IsmServiceDefService;
import com.sec.etech.ism.util.IsmStringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class IsmSendComponentRouteCompleteSetsServiceImpl implements IsmMethodService {
    @Resource
    JdbcTemplate jdbcTemplate;
    @Resource
    IsmCommonService ismCommonService;
    @Resource
    IsmAppSettingService ismAppSettingService;
    @Resource
    IsmServiceDefService ismServiceDefService;

    @Override
    public JSONObject call(String sysCode, String serviceCode, JSONObject busObj) throws Exception {
        JSONObject result = new JSONObject();
        String msg = this.sendComponentRouteCompleteSets(sysCode, serviceCode, busObj);
        result.put("flag", msg);
        result.put("msg", msg);
        return result;
    }


    private String sendComponentRouteCompleteSets(String sysCode, String serviceCode, JSONObject busObj) {
        Map<String, String> logMap = new HashMap<>(5);
        //服务信息
        IsmServiceDef serviceDef = null;
        try {
            serviceDef = ismServiceDefService.getByCode(serviceCode);
            //调用的应用信息
            IsmAppSetting appSetting = ismAppSettingService.getByCode(sysCode);
            String url = appSetting.getAppAddress() + "prodInfo/completeSetSleeve";
            logMap.put("appName", this.methodName());
            logMap.put("url", url);
            //查询数据部套下零件成套状态信息
            List<JSONObject> pcsParams = this.getComponentRouteCompleteSets(busObj);
            ismCommonService.checkResult(url, JSONObject.toJSONString(pcsParams), serviceDef, null,
                    busObj.toJSONString(), this.methodName(), logMap);
            return "success";
        } catch (Exception e) {
            log.error("部套下零件成套状态推送PCS接口异常。serviceDef.getCode()={}，serviceDef.getName()={}，logMap={}",
                    serviceDef.getCode(), serviceDef.getName(), logMap);
            e.printStackTrace();
            return "部套下零件成套状态推送PCS接口异常，请联系管理员处理！";
        }
    }

    private List<JSONObject> getComponentRouteCompleteSets(JSONObject busObj) {

        List<JSONObject> componentInfoList = new ArrayList<>();//部套下零件的成套状态信息
        //1.查询部套信息
        List<String> comRouteIdList = busObj.get("comRouteIdList") != null ? (List<String>) busObj.get("comRouteIdList") : new ArrayList<>();
        List<Map<String, Object>> componentList = null;
        if (comRouteIdList == null || comRouteIdList.size() == 0) {//查询机组下所有原创部套

            String sql = "select distinct t1.componentid,t3.componentnum,t3.componentname,t3.component_SAPnum " +
                    "from proj_orders_component t1 join proj_plantask t2 on t1.componentid=t2.plantaskid " +
                    " left join prod_component t3 on t1.componentid=t3.componentid " +
                    "where t1.ordersid=? and t2.projectid=? and t1.active=1";
            componentList = jdbcTemplate.queryForList(sql, busObj.get("ordersid"), busObj.get("projectid"));
        } else {
            String sql = "select componentid,componentnum,componentname,component_SAPnum " +
                    "from prod_component where componentid in (select componentid from proj_component_route where routeid=?)";
            componentList = jdbcTemplate.queryForList(sql, comRouteIdList.get(0));
        }
        if (componentList.isEmpty()) {
            return new ArrayList<>();
        }
        //2.查询部套下零件成套状态信息
        for (Map<String, Object> map : componentList) {
            //部套属性信息
            JSONObject object = new JSONObject();
            object.put("componentNum", map.get("componentnum"));
            object.put("componentName", map.get("componentname"));
            object.put("componentSAPnum", map.get("component_SAPnum"));
            //获取部套下零件信息
            List<JSONObject> partsCompleteSetList = new ArrayList<>();
            String sql = "select t1.partsid,t1.partsnum,t1.partsname,t1.drawing_logo,t1.parts_SAPnum,t2.numcode," +
                    " t2.completeset_id,t2.testrun_id " +
                    "from prod_parts t1 join proj_component_route t2 on t1.partsid=t2.partsid ";
            if (comRouteIdList == null || comRouteIdList.size() == 0) {
                sql = sql + "where t2.active=1 and t2.partsid>0 and t2.componentid>0 and t2.componentid=? " +
                        "order by t1.generalview desc,t2.numcode_order,t1.partsnum";
            } else {
                sql = sql + "where t2.active=1 and t2.partsid>0 and t2.componentid>0 and t2.componentid=? " +
                        " and t2.routeid in ('" + String.join("','", comRouteIdList) + "') " +
                        "order by t1.generalview desc,t2.numcode_order,t1.partsnum";
            }
            List<Map<String, Object>> partsList = jdbcTemplate.queryForList(sql, map.get("componentid"));
            if (partsList != null && partsList.size() > 0) {
                for (Map<String, Object> partsMap : partsList) {
                    JSONObject partsObj = new JSONObject();
                    partsObj.put("numCode", IsmStringUtil.getStrNullToEmpty(partsMap.get("numcode")));
                    partsObj.put("partsNum", partsMap.get("partsnum"));
                    partsObj.put("partsName", partsMap.get("partsname"));
                    partsObj.put("materialNo", partsMap.get("parts_SAPnum"));//零件物料号
                    //成套状态 {0:"无状态",1:"上台件",2:"装箱件",3:"装配退",4:"部套装配",5:"上台(装箱)",6:"无状态"}
                    Integer completeSetId = partsMap.get("completeset_id") != null ? Integer.parseInt(partsMap.get("completeset_id").toString()) : null;
                    String completeSetName = null;
                    if (completeSetId != null && completeSetId == 0) {
                        completeSetName = "无状态";
                    } else if (completeSetId != null && completeSetId == 1) {
                        completeSetName = "上台件";
                    } else if (completeSetId != null && completeSetId == 2) {
                        completeSetName = "装箱件";
                    } else if (completeSetId != null && completeSetId == 3) {
                        completeSetName = "装配退";
                    } else if (completeSetId != null && completeSetId == 4) {
                        completeSetName = "部套装配";
                    } else if (completeSetId != null && completeSetId == 5) {
                        completeSetName = "上台(装箱)";
                    } else if (completeSetId != null && completeSetId == 6) {
                        completeSetName = "无状态";
                    }
                    partsObj.put("completeSetName", completeSetName);//成套状态
                    //试车属性 {0:"不参与试车",1:"试车",2:"试车退",3:"不参与试车"}
                    Integer testRunId = partsMap.get("testrun_id") != null ? Integer.parseInt(partsMap.get("testrun_id").toString()) : null;
                    String testRunName = null;
                    if (testRunId != null && testRunId == 0) {
                        testRunName = "不参与试车";
                    } else if (testRunId != null && testRunId == 1) {
                        testRunName = "试车";
                    } else if (testRunId != null && testRunId == 2) {
                        testRunName = "试车退";
                    } else if (testRunId != null && testRunId == 3) {
                        testRunName = "不参与试车";
                    }
                    partsObj.put("testRunName", testRunName);//试车属性
                    Integer drawingLogo = partsMap.get("drawing_logo") != null ? (Integer) partsMap.get("drawing_logo") : null;
                    if (drawingLogo != null && drawingLogo == 1) {
                        partsObj.put("drawingFlag", "T");//图纸标识
                    } else {
                        partsObj.put("drawingFlag", "L");//图纸标识
                    }
                    partsCompleteSetList.add(partsObj);
                }
            }
            object.put("partsCompleteSetList", partsCompleteSetList);
            componentInfoList.add(object);
        }
        return componentInfoList;
    }

    @Override
    public String methodName() {
        return "sendComponentRouteCompleteSets";
    }
}
